package com.srwl.mytx.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.bm.library.Info;
import com.bm.library.PhotoView;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.PickPictureAdapter;
import com.srwl.mytx.domain.MyFile;

import java.util.ArrayList;
import java.util.List;

public class PickPicturesListView extends RecyclerView implements PickPictureAdapter.InteractionListener {
    private static final String TAG = "PickPicturesListView";
    private Context context;
    private PickPictureAdapter pickPictureadapter;
    private List<MyFile> totalSelectFile = new ArrayList<>();//所有选中的文件集合
    private PickPictureAdapter.InteractionListener listener;
    private List<MyFile> itemList = new ArrayList<>();//用于显示的数据集，里面包含生成的添加数据的item 和选中的文件
    private int pictureLimit = 9;//默认设置9张图片
    private int videoLimit = 1;//默认设置1个视频文件
    private boolean selectOnlyOneType;


    public PickPicturesListView(Context context) {
        super(context);
        this.context = context;
    }

    public PickPicturesListView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    public void init(List<MyFile> totalSelectFile, int videoLimit, int pictureLimit, boolean selectOnlyOneType, PickPictureAdapter.InteractionListener listener) {
        this.videoLimit = videoLimit;
        this.pictureLimit = pictureLimit;
        this.selectOnlyOneType = selectOnlyOneType;
        init(totalSelectFile, listener);
    }

    public void init(List<MyFile> totalSelectFile, PickPictureAdapter.InteractionListener listener) {

        this.totalSelectFile = totalSelectFile;
        this.listener = listener;
        //行数
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, cols);
        setLayoutManager(gridLayoutManager);
        generateItemList();
        pickPictureadapter = new PickPictureAdapter(context, itemList, this);
        setAdapter(pickPictureadapter);
        ItemTouchHelper touchHelper = new ItemTouchHelper(new MyItemTouchHelperCallBack());
        touchHelper.attachToRecyclerView(this);
    }


    @Override
    public void onSelectRemoteFile() {
        listener.onSelectRemoteFile();
    }

    @Override
    public void onPickNewPicture(int position) {
        listener.onPickNewPicture(position);
    }

    @Override
    public void onShowBigImage(MyFile targetFile, Info info) {
        listener.onShowBigImage(targetFile, info);
    }

    @Override
    public void onCreateVideo(View view, int position) {
        listener.onCreateVideo(view, position);
    }

    @Override
    public void onShowVideo(MyFile targetVideoFile, int position) {
        listener.onShowVideo(targetVideoFile, position);
    }


    @Override
    public void onPictureRemove(int position, MyFile targetPictureFile) {
        totalSelectFile.remove(targetPictureFile);
        refresh();
        listener.onPictureRemove(position, targetPictureFile);
    }

    @Override
    public void onVideoRemove(int position, MyFile targetVideoFile) {
        totalSelectFile.remove(targetVideoFile);
        // itemList.get(position).setType(MyFile.FILE_TYPE_ADD_VIDEO);
        //videoPath = null;
        // pickPictureadapter.notifyItemChanged(position);//不能只刷新一个，这样
        refresh();
        listener.onVideoRemove(position, targetVideoFile);
    }

    public int getIndex(MyFile myFile) {
        return itemList.indexOf(myFile);
    }


    public class MyItemTouchHelperCallBack extends ItemTouchHelper.Callback {
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int targetPosition = viewHolder.getAdapterPosition();
            MyFile dragFile = itemList.get(targetPosition);
            //如果被拖拽的是图片，才能拖拽，视频也不能拖拽，让视频显示在最前面
            if (dragFile.getType() == MyFile.FILE_TYPE_PICTURE) {
                int dragFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                int swipeFlags = ItemTouchHelper.ACTION_STATE_IDLE;
                return makeMovementFlags(dragFlags, swipeFlags);
            } else {
                return ItemTouchHelper.ACTION_STATE_IDLE;
            }

        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            int targetItemPosition = target.getAdapterPosition();
            MyFile targetFile = itemList.get(targetItemPosition);
            int dragItemPosition = viewHolder.getAdapterPosition();
            MyFile dragFile = itemList.get(dragItemPosition);
            //如果目标文件是图片，移动当前的托抓项到目标位置
            if (targetFile.getType() == MyFile.FILE_TYPE_PICTURE) {
                pickPictureadapter.notifyItemMoved(dragItemPosition, targetItemPosition);
                itemList.remove(dragFile);
                itemList.add(targetItemPosition, dragFile);
                movePosition(targetFile, dragFile);
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            Log.d(TAG, "onSwiped: 滑动删除，，，，");

            totalSelectFile.remove(viewHolder.getAdapterPosition() - 1);
            pickPictureadapter.notifyDataSetChanged();
        }
    }

    /**
     * 移动位置
     *
     * @param targetFile
     * @param dragFile
     */
    void movePosition(MyFile targetFile, MyFile dragFile) {
        int targetPosition = totalSelectFile.indexOf(targetFile);
        totalSelectFile.remove(dragFile);
        totalSelectFile.add(targetPosition, dragFile);

    }

    /**
     * 刷新
     */
    public void refresh() {
        generateItemList();
        pickPictureadapter.notifyDataSetChanged();
    }

    /**
     * 刷新视频
     */
    public void refreshVideoItem(MyFile videoFile) {

//        itemList.remove(1);
//        itemList.add(1, videoFile);
        pickPictureadapter.notifyItemChanged(1);
    }

    private void generateItemList() {
        itemList.clear();
        int videoCount = 0;
        int pictureCount = 0;
        for (MyFile myFile : totalSelectFile) {
            if (myFile.getType() == MyFile.FILE_TYPE_PICTURE) {
                pictureCount++;
            } else {
                videoCount++;
            }
        }
        if (selectOnlyOneType) {
            if ((videoCount==0&& totalSelectFile.size() < pictureLimit)||(pictureCount==0&&totalSelectFile.size()<videoLimit)) {
                itemList.add(0, new MyFile(MyFile.FILE_TYPE_SELECT_REMOTE_FILE));
            }
            if (videoCount < videoLimit && pictureCount == 0) {
                itemList.add(1, new MyFile(MyFile.FILE_TYPE_ADD_VIDEO));
            }
        } else {

            if (totalSelectFile.size() < pictureLimit + videoLimit) {
                itemList.add(0, new MyFile(MyFile.FILE_TYPE_SELECT_REMOTE_FILE));
            }
            if (videoCount < videoLimit) {
                itemList.add(1, new MyFile(MyFile.FILE_TYPE_ADD_VIDEO));
            }
        }
        itemList.addAll(totalSelectFile);
        if (selectOnlyOneType) {
            if (pictureCount < pictureLimit&&videoCount==0) {
                itemList.add(new MyFile(MyFile.FILE_TYPE_ADD_PICTURE));
            }
        } else {
            if (pictureCount < pictureLimit) {
                itemList.add(new MyFile(MyFile.FILE_TYPE_ADD_PICTURE));
            }

        }


    }

    public  Info getPositionInfo(MyFile myFile){
        int index = itemList.indexOf(myFile);

        PickPictureAdapter.ViewHolder viewHolder = (PickPictureAdapter.ViewHolder) getChildViewHolder(getChildAt(index));

        return PhotoView.getImageViewInfo(viewHolder.image);
    }

}
